<template>
  <view class="container">
    <form @submit="handleSubmit">
      <!-- 维修方式 -->
      <view class="form-section">
        <text class="section-title">维修方式</text>
        <radio-group class="radio-group" @change="handleMethodChange">
          <label class="radio-item">
            <radio value="0" checked /> 到店维修
          </label>
          <label class="radio-item">
            <radio value="1" /> 上门取车
          </label>
        </radio-group>
        
		
		
        <!-- 上门地址 -->
        <view v-if="showPickup" class="input-group">
          <input 
            class="input" 
            placeholder="请输入取车地址" 
            v-model="formData.pickupLocation"
          />
        </view>
      </view>

      <!-- 客户信息 -->
      <view class="form-section">
        <text class="section-title">客户信息</text>
        <view class="user-info">
          <text>姓名：{{ userInfo.name || '加载中...' }}</text>
          <text>电话：{{ userInfo.phone || '请先登录' }}</text>
        </view>
      </view>
	  
	   <!-- 预约时间选择 -->
	        <view class="form-section">
	          <text class="section-title">预约时间</text>
	          <uni-datetime-picker
	            type="datetime"
	            :start="new Date().getTime()"
	            :end="new Date(2030, 12, 30).getTime()"
	            v-model="formData.appointmentDate"
	            placeholder="请选择预约时间"
	          />
	        </view>

      <!-- 车辆信息 -->
      <view class="form-section">
        <text class="section-title">车辆信息</text>
        <picker 
          class="input" 
          @change="handleVehicleChange" 
          :value="vehicleIndex" 
          :range="vehicleTypes"
        >
          <view class="picker">
            {{ vehicleTypes[vehicleIndex] || '请选择车辆类型' }}
          </view>
        </picker>
        <input 
          class="input" 
          placeholder="请输入车牌号" 
          v-model="formData.plateNumber"
          maxlength="8"
        />
      </view>

      <!-- 照片上传 -->
      <view class="form-section">
        <text class="section-title">照片上传</text>
        <view class="upload-group">
          <!-- 整车照片 -->
         <view class="upload-item" @click="uploadPhoto('vehicle')">
           <uni-icons v-if="!formData.vehicleImage" 
                      type="plusempty" 
                      size="32" 
                      color="#ccc"></uni-icons>
           <text class="upload-text">整车照片</text>
           <image 
             v-if="formData.vehicleImage" 
             :src="formData.vehicleImage" 
             class="preview-image"
             mode="aspectFit"
             @error="handleImageError('vehicle')"
           />
         </view>
          
          <!-- 维修部位照片 -->
         <view class="upload-item" @click="uploadPhoto('part')">
           <uni-icons v-if="formData.partImages.length < 1" 
                     type="plusempty" 
                     size="32" 
                     color="#ccc"></uni-icons>
           <text class="upload-text">维修部位照片</text>
           <view class="part-preview">
             <image 
               v-for="(img, index) in formData.partImages" 
               :key="index"
               :src="img" 
               class="preview-image"
               mode="aspectFit"
               @error="handleImageError('part', index)"
             />
           </view>
         </view>
		  
        </view>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" form-type="submit">提交预约</button>
    </form>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const storeId = ref('') // 来自上个页面的门店ID
const memberId = ref("")
const vehicleTypes = ['小型汽车', 'SUV', 'MPV', '货车']
const vehicleIndex = ref(0)
const showPickup = ref(false)

 
// 表单数据
const formData = reactive({
  maintenanceMethod: '0', // 维修方式
  pickupLocation: '',    // 上门地址
  vehicleType: '',       // 车辆类型
  plateNumber: '',       // 车牌号
  appointmentDate: '',   // 预约时间
  vehicleImage: '',      // 整车照片
  partImages: [],       // 维修部位照片(最多2张)
  submitDate: '',         // 提交时间
  recordStatus: 0       //状态字段  设置默认值0
})

// 用户信息（模拟数据）
const userInfo = reactive({
  name: '张三',
  phone: '13800138000'
})

// 处理维修方式变化
const handleMethodChange = (e) => {
  formData.maintenanceMethod = e.detail.value
  showPickup.value = e.detail.value === '1'
}

// 处理车辆类型选择
const handleVehicleChange = (e) => {
  vehicleIndex.value = e.detail.value
  formData.vehicleType = vehicleTypes[e.detail.value]
}

// 图片上传处理
const uploadPhoto = async (type) => {
  try {
    // 选择图片
    const chooseRes = await uni.chooseImage({
      count: type === 'vehicle' ? 1 : 2,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })

    // 显示上传状态
    uni.showLoading({ title: '上传中...', mask: true })

    // 批量上传到OSS
    const uploadTasks = chooseRes.tempFiles.map(file => 
      uni.uploadFile({
        url: 'http://localhost:9300/file', // 替换为实际接口地址
        filePath: file.path,
        name: 'file',
        formData: {
          // 可以添加其他参数，比如用户ID
          'userId': memberId.value 
        }
      })
    )

    // 等待所有上传完成
    const uploadResults = await Promise.all(uploadTasks)
    
    // 处理上传结果
    const urls = uploadResults.map(result => {
      if(result.statusCode !== 200) {
        throw new Error('上传失败')
      }
      return result.data // 直接返回OSS URL字符串
    })

    // 更新表单数据
    if(type === 'vehicle') {
      formData.vehicleImage = urls[0]
    } else {
      formData.partImages = urls.slice(0,2)
    }

  } catch (error) {
    console.error('上传错误:', error)
    uni.showToast({ 
      title: error.message || '上传失败', 
      icon: 'none',
      duration: 3000
    })
  } finally {
    uni.hideLoading()
  }
}

const handleImageError = (type, index) => {
  uni.showToast({ title: '图片加载失败', icon: 'none' })
  
  if(type === 'vehicle') {
    formData.vehicleImage = ''
  } else {
    formData.partImages.splice(index, 1)
  }
}

// 生成订单号
const generateOrderNo = () => {
  const date = new Date()
  const timestamp = date.getTime()
  const random = Math.floor(Math.random() * 1000)
  return `NO${timestamp}${random}`
}

// 表单提交
const handleSubmit = async () => {
  // 表单验证
  if (!formData.plateNumber || !formData.appointmentDate) {
    return uni.showToast({ title: '请填写完整信息', icon: 'none' })
  }
  if (formData.maintenanceMethod === '1' && !formData.pickupLocation) {
    return uni.showToast({ title: '请填写取车地址', icon: 'none' })
  }
  
  // 转换日期格式（核心修复部分）
     const formatDate = (dateStr) => {
       // 处理uni-datetime-picker返回的时间戳
       if (typeof dateStr === 'number') {
         return new Date(dateStr).toISOString()
       }
       // 处理字符串格式（兼容多平台）
       return new Date(
         dateStr.replace(/-/g, '/') // iOS兼容处理
       ).toISOString()
     }
 
     // 获取ISO格式时间
     const isoDate = formatDate(formData.appointmentDate)
     const selectedTime = new Date(isoDate).getTime()
     const currentTime = Date.now()
     const twoHoursLater = currentTime + 7200000
 
     // 校验时间规则
     if (selectedTime < currentTime) {
       throw new Error('不能选择过去的时间')
     }
     if (selectedTime < twoHoursLater) {
       throw new Error('请至少提前2小时预约')
     }
     const hours = new Date(selectedTime).getHours()
     if (hours < 9 || hours >= 20) {
       throw new Error('请选择9:00-20:00之间的时间')
     }
	 
	 // 生成订单号保存到变量
	   const maintenanceNo = generateOrderNo()


  // 准备提交数据
  const submitData = {
    ext1: storeId.value,             // 门店ID
    ext2: formData.vehicleType,      // 车辆类型
    ext3: formData.plateNumber,      // 车牌号
    maintenanceNo: maintenanceNo,// 订单号
    maintenanceMethod: formData.maintenanceMethod,
    appointmentDate: isoDate, //预约日期
    submitDate: new Date().toISOString(),
    vehicleImage: formData.vehicleImage,
    partImage1: formData.partImages[0] || '',
    partImage2: formData.partImages[1] || '',
    pickupLocation: formData.pickupLocation,
	memberId: memberId.value ,//会员id
	recordStatus: formData.recordStatus 
	
  }

  try {
    const { data: res } = await uni.request({
      url: 'http://localhost:9587/repairRecord',
      method: 'POST',
      data: submitData,
      header: {
        'Content-Type': 'application/json'
      }
    })

    if(res.code === 200) {
      uni.showToast({ title: '提交成功' })
      setTimeout(() => {
        uni.navigateTo({
            url: `/pages/order/order?orderId=${maintenanceNo}`
          })
      }, 1500)
    } else {
      throw new Error(res.message || '提交失败')
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '请求失败',
      icon: 'none'
    })
  }
}

// 获取页面参数
onLoad((options) => {
	 memberId.value = uni.getStorageSync('memberId') || ''
  if(options.storeId) {
    storeId.value = options.storeId
  }
})
</script>

<style scoped>
.container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.form-section {
  background: #fff;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
}

.section-title {
  display: block;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-item {
  display: flex;
  align-items: center;
}

.input {
  height: 44px;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 0 10px;
  margin-bottom: 12px;
}

.picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 44px;
  color: #666;
}

.upload-group {
  display: flex;
  gap: 15px;
}

.upload-item {
  position: relative;
    padding: 20rpx;
    border: 2rpx dashed #e5e5e5;
    border-radius: 12rpx;
    margin-bottom: 30rpx;
    min-height: 240rpx;
}

.upload-text {
  font-size: 12px;
  color: #999;
  margin-top: 6px;
}

.submit-btn {
  background: #007AFF;
  color: #fff;
  border-radius: 25px;
  margin-top: 20px;
}

/* 保持原有样式基础上新增 */
.user-info {
  padding: 15px;
  background: #f8f8f8;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-image {
 width: 100%;
   height: 200rpx;
   border-radius: 8rpx;
   margin-top: 20rpx;
   background-color: #f5f5f5;
}

.part-preview {
 display: grid;
   grid-template-columns: repeat(2, 1fr);
   gap: 20rpx;
   margin-top: 20rpx;
}

.input-group {
  margin-top: 12px;
}

.uni-datetime-picker {
  width: 100%;
  margin: 10px 0;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  padding: 12px;
  box-sizing: border-box;
}

.uni-datetime-picker__input {
  color: #333;
  font-size: 14px;
}
</style>